package com.fitzone.web.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fitzone.common.enums.BusinessType;
import com.fitzone.common.exception.LoginFailedException;
import com.fitzone.common.result.Result;
import com.fitzone.model.dto.CoachPageDTO;
import com.fitzone.model.dto.CoachDTO;
import com.fitzone.model.entity.Coach;
import com.fitzone.model.entity.CoachPhoto;
import com.fitzone.model.entity.Store;
import com.fitzone.model.entity.SysUser;
import com.fitzone.model.vo.CoachVO;
import com.fitzone.web.annotation.Log;
import com.fitzone.web.service.CoachPhotoService;
import com.fitzone.web.service.CoachService;
import com.fitzone.web.service.StoreService;
import com.fitzone.web.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/coach")
@RequiredArgsConstructor
@Api(tags = "教练管理")
public class CoachController {
    private final CoachService coachService;
    private final StoreService storeService;
    private final SysUserService sysUserService;
    private final CoachPhotoService coachPhotoService;

    @Log(title = "教练管理", businessType = BusinessType.INSERT)
    @PostMapping
//    @PreAuthorize("hasAuthority('bnt.store.list')")
    @ApiOperation("添加操作")
    public Result save(@RequestBody CoachDTO coachDTO){
        coachService.saveCoach(coachDTO);
        return Result.ok();
    }

    @Log(title = "教练管理", businessType = BusinessType.UPDATE)
    @PutMapping
//    @PreAuthorize("hasAuthority('bnt.store.list')")
    @ApiOperation("修改操作")
    public Result update(@RequestBody CoachDTO coachDTO) {
        coachService.updateCoach(coachDTO);
        return Result.ok();
    }

    @Log(title = "教练管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
//    @PreAuthorize("hasAuthority('bnt.store.list')")
    @ApiOperation("删除操作")
    public Result delete(@PathVariable Long id) {
        LambdaQueryWrapper<CoachPhoto> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(CoachPhoto::getCoachId, id);
        coachPhotoService.remove(queryWrapper);
        coachService.removeById(id);
        return Result.ok();
    }

    @ApiOperation("查询操作")
    @GetMapping("/{page}/{limit}")
    public Result<Page> page(CoachPageDTO coachPageDTO) {
        Long principal = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null) {
            throw new LoginFailedException("账号错误");
        }
        SysUser user = sysUserService.getById(principal);

        Page<Coach> pageInfo = new Page<>(coachPageDTO.getPage(), coachPageDTO.getLimit());
        Page<CoachVO> coachPageInfo = new Page<>();
        LambdaQueryWrapper<Coach> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(coachPageDTO.getCoachName() != null, Coach::getCoachName, coachPageDTO.getCoachName())
                .orderByDesc(Coach::getCreateTime)
                .eq(user.getStoreId() != null,Coach::getStoreId, user.getStoreId());
        coachService.page(pageInfo, queryWrapper);
        //对象的拷贝
        BeanUtils.copyProperties(pageInfo, coachPageInfo, "records");
        List<Coach> coach = pageInfo.getRecords();
        List<CoachVO> list = coach.stream().map(item -> {
            LambdaQueryWrapper<CoachPhoto> coachPhotoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            coachPhotoLambdaQueryWrapper.eq(CoachPhoto::getCoachId, item.getId());
            List<CoachPhoto> coachPhotos = coachPhotoService.list(coachPhotoLambdaQueryWrapper);

            CoachVO coachVO = new CoachVO();
            BeanUtils.copyProperties(item, coachVO);
            Long storeId = item.getStoreId();
            Store store = storeService.getById(storeId);
            String storeName = store.getStoreName();
            coachVO.setStoreName(storeName);

            ArrayList<Map<String, String>> cert = new ArrayList<>();
            ArrayList<Map<String, String>> personal = new ArrayList<>();
            for (CoachPhoto coachPhoto : coachPhotos) {
                HashMap<String, String> map = new HashMap<>();
                map.put("url", coachPhoto.getUrl());
                map.put("name", coachPhoto.getName());
                if (coachPhoto.getType() == 0) {
                    cert.add(map);
                } else {
                    personal.add(map);
                }
            }
            coachVO.setCert(cert);
            coachVO.setPersonal(personal);
            return coachVO;
        }).collect(Collectors.toList());
        coachPageInfo.setRecords(list);
        return Result.ok(coachPageInfo);
    }

    @ApiOperation(value = "根据id查询")
    @GetMapping("/{id}")
    public Result<CoachVO> getId(@PathVariable Long id) {
        CoachVO coachVO = coachService.getCoachById(id);
        return Result.ok(coachVO);
    }

    @Log(title = "教练管理", businessType = BusinessType.STATUS)
    @GetMapping("/updateStatus/{id}/{status}")
//    @PreAuthorize("hasAuthority('bnt.store.list')")
    @ApiOperation("修改状态")
    public Result updateStatus(@PathVariable Integer status, @PathVariable Long id) {
        coachService.updateStatus(status,id);
        return Result.ok();
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询所有")
//    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    public Result<List<Map>> getAll(){
        LambdaQueryWrapper<Coach> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Coach::getStatus,1);
        List<Coach> list = coachService.list(queryWrapper);

        List<Map> maps = new ArrayList<>();
        for (Coach coach : list) {
            Map map = new HashMap();
            map.put("id",coach.getId());
            map.put("coachName",coach.getCoachName());
            maps.add(map);
        }
        return Result.ok(maps);
    }

}
